package com.taotao.game;

import com.rop.client.CompositeResponse;
import com.taotao.admin.MyRopClient;
import com.taotao.rop.database.domain.PlayGame;
import com.taotao.rop.database.domain.PlayGameRanking;
import com.taotao.rop.response.BaseResponse;
import com.taotao.rop.util.DateTimeUtil;
import com.taotao.wechat.game.FindWordGame2;
import com.taotao.wechat.util.ValidateUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * 找4G游戏控制器
 */
@Controller
@RequestMapping(value = "/findWord2")
public class FindWord2Controller {
    private Logger logger = LoggerFactory.getLogger(FindWord2Controller.class);
    @RequestMapping(value = "/init", method = RequestMethod.POST)
    @ResponseBody
    public Object init(HttpServletRequest request) {
        String appId = request.getParameter("appId");
        String openId = request.getParameter("openId");
        String tel = request.getParameter("tel");

        int maxRound = 1, currentRound = 3, maxTimeout = 40;
        if (StringUtils.isNotBlank(appId) && StringUtils.isNotBlank(openId)
                && StringUtils.isNotBlank(tel) && ValidateUtil.isYiDong(tel) == 0) {
            //游戏二
            FindWordGame2 findWordGame2 = new FindWordGame2();
            maxTimeout = 60;
            boolean isMember = findWordGame2.isMember(openId, appId, findWordGame2.getMemberStatus());
            if (isMember) {
                maxRound = 2;
            } else {
                maxRound = 1;
            }

            String telResult = findWordGame2.telJoinCountToday(tel, openId, appId);
            if (!StringUtils.isBlank(telResult)) {
                currentRound = 3;
                if (telResult.contains(FindWordGame2.MSG_TEL_IS_RANKING)) {
                    currentRound = -1;  //表示已经中奖
                } else if (telResult.equalsIgnoreCase(FindWordGame2.MSG_TEL_IS_USED)) {
                    currentRound = -2; //表示手机号已经被使用
                } else if (telResult.equalsIgnoreCase(FindWordGame2.MSG_TEL_IS_USED_NO_MEMBER)) {
                    currentRound = -3;  //表示手机号已经被使用，且是非会员的时候
                }
            } else {
                String wechatResult = findWordGame2.wechatJoinCountToday(openId, appId);
                if (StringUtils.isBlank(wechatResult)) {
                    currentRound = 1;
                } else if (findWordGame2.isMemberTimes.equals(wechatResult)) {
                    currentRound = 2;
                } else {
                    currentRound = 3;
                }
            }
        }
        return generateInitParam(maxTimeout, maxRound, currentRound);
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public Object save(HttpServletRequest request) {
        //不是微信浏览器
        if (request.getHeader("user-agent").toLowerCase().indexOf("micromessenger") <= 0) {
            return "{\"result\":\"请关注内蒙古移动微信号参加活动\"}";
        }
        //不是合法地址过来的请求
        logger.error(request.getHeader("Origin"));
        if (!MyRopClient.BASE_URL.equalsIgnoreCase(request.getHeader("Origin"))) {
            return "{\"result\":\"您的操作非法，请关注内蒙古移动微信号参加活动\"}";
        }

        String score = request.getParameter("score");
        String appId = request.getParameter("appId");
        String openId = request.getParameter("openId");
        String tel = request.getParameter("tel");
        String sign = request.getParameter("sign");

        //验证签名
        if (StringUtils.isNotBlank(sign) && sign.equals(ValidateUtil.sign(score, appId, openId, tel, "nmgwxyytbypjnmzxhr"))) {
            if (StringUtils.isNotBlank(score) && StringUtils.isNotBlank(appId) && StringUtils.isNotBlank(openId)
                    && StringUtils.isNotBlank(tel) && ValidateUtil.isYiDong(tel) == 0) {
                FindWordGame2 findWordGame2 = new FindWordGame2();
                String wechatResult = findWordGame2.wechatJoinCountToday(openId, appId);
                if ((StringUtils.isBlank(wechatResult) || findWordGame2.isMemberTimes.equals(wechatResult))
                        && StringUtils.isBlank(findWordGame2.telJoinCountToday(tel, openId, appId))) {
                    endGame(appId, openId, findWordGame2.getNickName(), tel, score, "", false);
                }
            }
            return "{\"result\":\"success\"}";
        } else {
            return "{\"result\":\"请从正确渠道合法方式参加活动，关注内蒙古移动微信号即可\"}";
        }
    }

    @RequestMapping(value = "/score", method = RequestMethod.POST)
    @ResponseBody
    public Object score(HttpServletRequest request) {
        String tel = request.getParameter("tel");
        PlayGameRanking playGameRanking = new PlayGameRanking();

        if (StringUtils.isNotBlank(tel) && ValidateUtil.isYiDong(tel) == 0) {
            FindWordGame2 findWordGame2 = new FindWordGame2();
            PlayGameRanking condition = new PlayGameRanking();
            condition.setGameName(findWordGame2.getNickName());
            condition.setTel(tel);
            CompositeResponse<BaseResponse> response = MyRopClient.getRopClient("").buildClientRequest()
                    .post(condition, BaseResponse.class, "playGameRanking.ranking", "1.0");
            if (response.isSuccessful()) {
                BaseResponse baseResponse = response.getSuccessResponse();
                if (baseResponse.getSuccess()) {
                    List<LinkedHashMap<String, Object>> respData = (List<LinkedHashMap<String, Object>>) baseResponse.getData();
                    if (respData == null || respData.size() == 0) {
                        playGameRanking.setPrize(-1);   //未中奖

                        PlayGame isJoinTodayCondition = new PlayGame();
                        isJoinTodayCondition.setGameName(findWordGame2.getNickName());
                        isJoinTodayCondition.setTel(tel);
                        CompositeResponse<BaseResponse> isJoinTodayResponse = MyRopClient.getRopClient("").buildClientRequest()
                                .post(isJoinTodayCondition, BaseResponse.class, "playGame.getTelJoinCountToday", "1.0");
                        if (isJoinTodayResponse.isSuccessful()) {
                            BaseResponse isJoinTodayBaseResponse = isJoinTodayResponse.getSuccessResponse();
                            if (isJoinTodayBaseResponse.getSuccess()) {
                                int count = 0;
                                try {
                                    count = Integer.parseInt(isJoinTodayBaseResponse.getData().toString());
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                if (count > 0) {
                                    playGameRanking.setPrize(-2); //未中奖用户今日继续参加
                                }
                            }
                        }
                    } else if (respData.size() > 0) {
                        playGameRanking.setPrize(Integer.parseInt(respData.get(0).get("prize").toString()));
                        playGameRanking.setFinishTime(Long.parseLong(respData.get(0).get("finishTime").toString()));
                        playGameRanking.setResult(respData.get(0).get("result").toString());
                    }
                    playGameRanking.setTel(tel);
                }
            }
        }
        return playGameRanking;
    }

    /**设置游戏初始化参数*/
    private String generateInitParam(Integer maxTimeout, Integer maxPlayRound, Integer currentPlayRound) {
        return String.format("{\"timeout\":%s, \"maxRound\":%s, \"currentRound\":%s}",
                maxTimeout, maxPlayRound, currentPlayRound);
    }

    private boolean endGame(String appId, String openId, String gameName, String tel, String result, String grade, boolean isRanking) {
        PlayGame condition = new PlayGame();
        condition.setAppId(appId);
        condition.setOpenId(openId);
        condition.setGameName(gameName);
        Date now = new Date();
        condition.setStartTime(DateTimeUtil.getDateStartMillis(now));
        condition.setEndTime(DateTimeUtil.getDateEndMillis(now));

        CompositeResponse<BaseResponse> response = MyRopClient.getRopClient("").buildClientRequest()
                .post(condition, BaseResponse.class, "playGame.list", "1.0");
        if (response.isSuccessful()) {
            BaseResponse baseResponse = response.getSuccessResponse();
            if (baseResponse.getSuccess()) {
                List<LinkedHashMap<String, Object>> respData = (List<LinkedHashMap<String, Object>>) baseResponse.getData();
                try {
                    PlayGame playGame = new PlayGame();
                    playGame.setResult(result);
                    Integer intGrade = null;
                    if (StringUtils.isNotBlank(grade) && StringUtils.isNumeric(grade)) {
                        intGrade = Integer.parseInt(grade);
                    }
                    playGame.setPrize(intGrade);
                    playGame.setTel(tel);
                    Long finishTime = DateTimeUtil.getDateMillis(new Date());
                    playGame.setFinishTime(finishTime);

                    if (isRanking) {
                        //插入排名表
                        PlayGameRanking playGameRanking = new PlayGameRanking(appId, openId, gameName, tel, result, intGrade, finishTime);
                        MyRopClient.getRopClient("").buildClientRequest()
                                .post(playGameRanking, BaseResponse.class, "playGameRanking.insertOrUpdate", "1.0");
                    }
                    if (respData != null && respData.size() > 0) {
                        if (respData.get(0).get("finishTime") != null) {
                            //新增一条游戏记录
                            playGame.setAppId(appId);
                            playGame.setOpenId(openId);
                            playGame.setGameName(gameName);
                            MyRopClient.getRopClient("").buildClientRequest()
                                    .post(playGame, BaseResponse.class, "playGame.insert", "1.0");
                            return true;
                        } else {
                            //更新游戏的后半段
                            Long id = Long.parseLong(respData.get(0).get("id").toString());
                            playGame.setId(id);
                            MyRopClient.getRopClient("").buildClientRequest()
                                    .post(playGame, BaseResponse.class, "playGame.end", "1.0");
                            return true;
                        }
                    } else {
                        //新增一条游戏记录
                        playGame.setAppId(appId);
                        playGame.setOpenId(openId);
                        playGame.setGameName(gameName);
                        MyRopClient.getRopClient("").buildClientRequest()
                                .post(playGame, BaseResponse.class, "playGame.insert", "1.0");
                        return true;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }
}
